<template>
  <div class="container">
    <el-row :gutter="10">
      <!-- <el-col :span="4" :xs="24">
        <el-card> -->
      <!-- search -->
      <!-- div class="head-container">
            <el-input
              v-model="deptName"
              :placeholder="$t('count.data.input.department')"
              clearable
              prefix-icon="el-icon-search"
              class="mb20"
            />
          </div> -->
      <!-- tree -->
      <!-- <el-scrollbar style="height:74vh;">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="true"
            :filter-node-method="filterNode"
            ref="tree"
            accordion
            node-key="id"
            :default-expanded-keys="[deptId]"
            highlight-current
            @node-click="handleNodeClick"/>
		</el-scrollbar>
        </el-card>
      </el-col> -->
      <el-col :span="24" :xs="24">
        <ul class="list">
          <!-- 当前在线数 -->
          <el-card>
            <li>
              <div class="itemContent oneline">
                <span class="iconfont">&#xe6b4;</span>
              </div>
              <div class="ml">
                <p>{{ $t('count.data.onLine') }}</p>
                <span>{{ getDevObj.online }}/{{ getDevObj.count }}</span>
              </div>
            </li>
          </el-card>
          <!-- 未在线 -->
          <el-card>
            <li>
              <div class="itemContent off-line">
                <span class="iconfont">&#xe912;</span>
              </div>
              <div class="ml">
                <p>{{ $t('count.data.offLine') }}</p>
                <span>{{ getDevObj.offline }}/{{ getDevObj.count }}</span>
              </div>
            </li>
          </el-card>
          <!-- 发送成功 -->
          <el-card>
            <li>
              <div class="itemContent send-success">
                <span class="iconfont">&#xe601;</span>
              </div>
              <div class="ml">
                <p>{{ $t('count.data.success') }}</p>
                <span
                  >{{ taksStatus.successTotle }}/{{
                    taksStatus.countTotal
                  }}</span
                >
              </div>
            </li>
          </el-card>
          <!-- 等待发送 -->
          <el-card>
            <li>
              <div class="itemContent send-faild">
                <span class="iconfont">&#xe6c6;</span>
              </div>
              <div class="ml">
                <p>{{ $t('count.data.wait') }}</p>
                <span
                  >{{ taksStatus.awaitTotal }}/{{ taksStatus.countTotal }}</span
                >
              </div>
            </li>
          </el-card>
        </ul>
        <!-- 统计信息 -->
        <div class="count" id="count">
          <!-- left 射线图容器 -->
          <el-card>
            <div
              style="height:69vh;width:100%;"
              ref="lineRef"
              id="myEchart"
            ></div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core'
// 引入柱状图图表，图表后缀都为 Chart
import { BarChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components'
// 标签自动布局，全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers'
import { getCount, getDevCount, getDayCount } from '@/api/system/count.js'
import i18n from '@/lang/index' // i8n
// const echarts = require('echarts')
const elementResizeDetectorMaker = require('element-resize-detector')

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
])
export default {
  name: 'Information',
  inject: ['reload'], // 局部刷新
  data () {
    return {
      isWatch: false,
      lineChart: undefined,
      deptName: undefined, // 部门名称
      deptOptions: undefined, // 部门树选项
      defaultProps: {
        children: 'children', // 指定子树为节点对象的某个属性值
        label: 'label' // 指定节点标签为节点对象的某个属性值
      },
      getDevObj: {
        online: 0,
        offline: 0,
        count: 0
      },
      deptId: undefined, // 部门id
      taskData: undefined,
      i18n: i18n,
      getTaskData: {
        awaitArr: [],
        countArr: [],
        coverArr: [],
        errorArr: [],
        successArr: [],
        timeArr: []
      },
      //图表数据
      taksStatus: {
        successTotle: undefined,
        countTotal: undefined,
        awaitTotal: undefined
      },
      // echarts配置项
      options: {
        animationDuration: 1500,
        color: ['#7cb5ec', '#90ed7d', '#f7a35c', '#434348', '#f56c6c'],
        // 标题
        title: {
          show: true,
          text: this.$t('count.data.title'),
          top: '0%'
        },
        // 提示
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
          // position: function (pt) {
          //   return [pt[0], '10%']
          // }
        },
        // 图裂
        legend: {
          top: '3%',
          // 任务总数 发送成功 等待发送 任务覆盖 发送失败
          data: [
            this.$t('count.data.legend.data.sum'),
            this.$t('count.data.legend.data.success'),
            this.$t('count.data.legend.data.wait'),
            this.$t('count.data.legend.data.override'),
            this.$t('count.data.legend.data.fail')
          ]
        },
        // 网格
        grid: {
          left: '2%',
          right: '4%',
          bottom: '5%',
          top: '16%',
          containLabel: true
        },
        // 工具
        toolbox: {
          show: true, // 是否显示工具栏组件
          showTitle: true, // 是否在鼠标 hover 的时候显示每个工具 icon 的标题
          //   right: '2.5%',
          // 各工具配置项
          feature: {
            // 数据视图
            dataView: {
              show: false,
              title: '数据视图',
              iconStyle: {
                borderColor: '#1e90ff'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#1e90ff'
                }
              }
            },
            // dataZoom: {}, // 数据区域缩放。目前只支持直角坐标系的缩放。
            // 切换视图类型
            magicType: {
              show: true,
              type: ['line', 'bar'],
              title: { line: '切换为折线图', bar: '切换为柱状图' },
              iconStyle: {
                borderColor: '#22bb22'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#22bb22'
                }
              }
            },
            // 刷新数据
            restore: {
              show: true, // 显示工具
              title: '刷新', // 标题
              iconStyle: {
                borderColor: '#d2691e'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#d2691e'
                }
              }
            },
            // 保存图片
            saveAsImage: {
              show: true,
              title: '保存图片',
              iconStyle: {
                borderColor: '#4b0082'
              },
              emphasis: {
                iconStyle: {
                  borderColor: '#4b0082'
                }
              }
            }
          }
        },
        // x轴
        xAxis: [
          {
            type: 'category',
            offset: 15,
            position: 'bottom',
            offset: 5, // X 轴相对于默认位置的偏移
            axisTick: {
              length: 7,
              alignWithLabel: false // 可以保证刻度线和标签对齐
            },
            boundaryGap: true,
            data: [],
            axisLine: {
              onZero: false,
              lineStyle: {
                color: '#0094ff'
              }
            },
            axisPointer: {
              shadowStyle: {
                // 填充的阴影颜色。
                color: 'rgba(150,150,150,0.3)'
              }
            }
          }
        ],
        // 直角坐标系 grid 中的 y 轴
        yAxis: {
          type: 'value',
          minInterval: 1,
          axisLabel: {
            formatter: '{value}'
          },
          // 是否显示坐标轴轴线
          axisLine: {
            show: false
          },
          // 是否显示坐标轴刻度
          axisTick: {
            show: false
          }
        },
        // 用于区域缩放
        dataZoom: [
          {
            show: true,
            height: 14,
            xAxisIndex: [0],
            type: 'inside',
            bottom: '8%',
            start: 0,
            end: 100,
            handleIcon:
              'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
            handleSize: '110%',
            handleStyle: {
              color: '#d3dee5'
            },
            textStyle: {
              color: '#000'
            },
            borderColor: '#90979c'
          }
        ],
        series: [
          {
            name: this.$t('count.data.legend.data.sum'),
            type: 'bar',
            barWidth: 20,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#fccb05'
                },
                {
                  offset: 1,
                  color: '#f5804d'
                }
              ]),
              borderRadius: 11
            },
            label: {
              show: true, //开启显示
              verticalAlign: 'middle',
              position: 'top',
              distance: 15,
              color: '#f79737',
              fontSize: 14,
              fontWeight: 700
            },
            data: []
          },
          {
            name: this.$t('count.data.legend.data.success'),
            type: 'bar',
            barWidth: 20,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#8bd46e'
                },
                {
                  offset: 1,
                  color: '#09bcb7'
                }
              ]),
              borderRadius: 11
            },
            label: {
              show: true, //开启显示
              verticalAlign: 'middle',
              position: 'top',
              distance: 15,
              color: '#7cd099',
              fontSize: 14,
              fontWeight: 700
            },
            data: []
          },
          {
            name: this.$t('count.data.legend.data.wait'),
            type: 'bar',
            smooth: true,
            barWidth: 20,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#248ff7'
                },
                {
                  offset: 1,
                  color: '#6851f1'
                }
              ]),
              borderRadius: 11
            },
            label: {
              show: true, //开启显示
              verticalAlign: 'middle',
              position: 'top',
              distance: 15,
              color: '#486ef4',
              fontSize: 14,
              fontWeight: 700
            },
            data: []
          },
          {
            name: this.$t('count.data.legend.data.override'),
            type: 'bar',
            barWidth: 20,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#fd7f3e'
                },
                {
                  offset: 1,
                  color: '#6851f1'
                }
              ]),
              borderRadius: 11
            },
            label: {
              show: true, //开启显示
              verticalAlign: 'middle',
              position: 'top',
              distance: 15,
              color: '#b56d99',
              fontSize: 14,
              fontWeight: 700
            },
            data: []
          },
          {
            name: this.$t('count.data.legend.data.fail'),
            type: 'bar',
            barWidth: 20,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: '#8194aa'
                },
                {
                  offset: 1,
                  color: '#e94242'
                }
              ]),
              borderRadius: 11
            },
            label: {
              show: true, //开启显示
              verticalAlign: 'middle',
              position: 'top',
              distance: 15,
              color: '#d0575d',
              fontSize: 14,
              fontWeight: 700
            },
            data: []
          }
        ]
      }
    }
  },
  // created() {
  //     window.addEventListener('resize', () => {
  //       if (this.lineChart) {
  //         this.lineChart.resize()
  //       }
  //     })
  //   },
  watch: {
    '$store.state.deptId': {
      handler (newval) {
        if (this.isWatch) {
          this.deptId = newval // 把点击获得的id赋值给queryParams模型id
          this.getDayCountData()
          this.getDevData()
          this.getCountData()
        }
      }
    },
    // 根据名称筛选部门树
    // deptName (val) {
    //   this.$refs.tree.filter(val)
    // },
    'i18n.locale': {
      handler (newVal, oldVal) {
        switch (newVal) {
          case 'zh':
            this.reload()
            break
          case 'en':
            this.reload()
            break
          case 'hk':
            this.reload()
            break
          default:
            break
        }
      }
    }
  },
  methods: {
    // 图表每天数据
    getDayCountData () {
      this.clearEcharts()
      getDayCount(this.deptId).then(res => {
        if (res.code == 200) {
          this.taskData = res.data
          res.data.forEach((item, index) => {
            this.options.series[2].data[index] = item.task_await
            this.options.series[0].data[index] = item.task_count
            this.options.series[3].data[index] = item.task_cover
            this.options.series[4].data[index] = item.task_error
            this.options.series[1].data[index] = item.task_success
            this.options.xAxis[0].data[index] = item.task_time.substring(0, 10)
          })
          this.options.dataZoom[0].start = 100 - 600 / res.data.length
          this.getlineData(this.options)
        }
      })
    },
    // 任务状态统计数据
    getCountData () {
      getCount(this.deptId).then(res => {
        if (res.code == 200) {
          // console.log(res)
          this.taksStatus.successTotle = res.data[0].task_success
            ? res.data[0].task_success
            : 0
          this.taksStatus.countTotal = res.data[0].task_count
            ? res.data[0].task_count
            : 0
          this.taksStatus.awaitTotal = res.data[0].task_await
            ? res.data[0].task_await
            : 0
        }
      })
    },
    // 设备数据
    getDevData () {
      getDevCount(this.deptId).then(res => {
        if (res.code == 200) {
          this.getDevObj.online = res.data.card_online
            ? res.data.card_online
            : 0
          this.getDevObj.offline = res.data.card_offline
            ? res.data.card_offline
            : 0
          this.getDevObj.count = res.data.card_count ? res.data.card_count : 0
        }
      })
    },
    clearEcharts () {
      this.options.series[2].data = []
      this.options.series[0].data = []
      this.options.series[3].data = []
      this.options.series[4].data = []
      this.options.series[1].data = []
      this.options.xAxis[0].data = []
    },
    // filterNode (value, data) {
    //   if (!value) return true
    //   return data.label.indexOf(value) !== -1
    // },
    // lineData
    getlineData (data) {
      // 初始化line
      if (
        this.lineChart != null &&
        this.lineChart != '' &&
        this.lineChart != undefined
      ) {
        this.lineChart.dispose()
      }
      // 基于准备好的dom，初始化echarts实例
      this.lineChart = echarts.init(this.$refs.lineRef)
      // 实例化line
      this.lineChart.setOption(data)
    }
  },
  mounted () {
    let that = this
    var erd = elementResizeDetectorMaker()
    erd.listenTo(document.getElementById('count'), function (element) {
      var width = element.offsetWidth
      var height = element.offsetHeight
      if (that.lineChart) {
        that.$nextTick(function () {
          //使echarts尺寸重置
          that.lineChart.resize()
        })
      }
    })
  },
  activated () {
    this.isWatch = true
    if (this.$store.state.deptId) {
      this.deptId = this.$store.state.deptId // 把点击获得的id赋值给queryParams模型id
      this.getDayCountData()
      this.getDevData()
      this.getCountData()
    }
  },
  deactivated () {
    this.isWatch = false
  }
}
</script>
<style lang="scss" scoped>
.container {
  .list {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-top: 0;
    padding-left: 0;
    text-align: center;
    .el-card {
      width: 23%;
    }
    li {
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .itemContent {
        font-size: 30px;
        border-radius: 50%;
        width: 70px;
        height: 70px;
        line-height: 70px;
      }
      .ml {
        font-size: 14px;
        font-weight: 700;
      }
    }

    .oneline {
      background-color: #99cc00;
    }

    .off-line {
      background-color: #a9acbd;
    }

    .send-success {
      background-color: #409eff;
    }

    .send-faild {
      background-color: #e6a23c;
    }
  }
  .count {
    width: 100%;
    height: 70vh;
    margin-top: 20px;
    // display: flex;
    // justify-content: space-around;
  }
}
::v-deep div.el-card__body {
  padding: 5px;
}
.iconfont {
  font-size: 30px;
}
</style>
